﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace KnowledgeEntity
{
   public class UserAccountFactory
   {
      public static UserAccount GetUserInstanceByID(int id)
      {
         string query = string.Format(@"select ID, Code, Name, Description, Role 
                                        from UserAccount
                                        where ID = {0}", id);

         return GetUserInstance(query);
      }

      public static UserAccount GetUserInstanceByCode(string code)
      {
         string query = string.Format(@"select ID, Code, Name, Description, Role 
                                        from UserAccount 
                                        where Code = '{0}'", code);

         return GetUserInstance(query);
      }

      public static bool LogOn(string code, string password)
      {
         string query = string.Format(@"select ID, Code , Name, Description, Role
                                       from UserAccount 
                                       where Code = '{0}' and Password = '{1}'", code, password);

         if (GetUserInstance(query).NoSuchUser) return false;

         return true;
      }

      private static UserAccount GetUserInstance(string query)
      {
         using (SqlDataReader userReader = DBHelper.SqlHelper.GetReader(query))
         {
            if (!userReader.HasRows || !userReader.Read()) return GetNoUser();

            int id = userReader.GetInt32(0);
            string code = userReader.GetString(1);
            string name = userReader.GetString(2);
            string description = userReader.GetString(3);
            int role = userReader.GetInt32(4);

            switch (role)
            {
               case 1:
                  return new UserAccount(id, code, name, description);
               case 2:
                  return new ProfessorAccount(id, code, name, description);
               case 3:
                  return new AdminAccount(id, code, name, description);
               default:
                  return GetNoUser();
            }
         }
      }

      private static UserAccount GetNoUser()
      {
         return new UserAccount(0, "NOUSER", "NOUSER", "No such user");
      }
   }
}
